/* 
批量下载文档md
- fileWriteTo(本地目标路径) 从包里复制文档到【目标路径】
node index.js 目标路径 是否翻译
*/
const fs = require('fs');
const path = require('path');
const request = require('request');

const {
    getFileData,
    fileWriteTo,
} = require('./../utils/file');
const {
    getFileName,
} = require('./../utils/filename');

const getArgv = () => {
    const arr = process.argv.slice(2);
    const o = {};
    if (arr[0]) o.path = arr[0];
    if (arr[1]) o.type = arr[1];// md / download
    if (o.path) {
        if (o.path.indexOf('http') === 0) {
            // 线上路径，暂不支持
        } else if (o.path.indexOf('file:') === 0  || o.path.indexOf(':') > -1) {
            // 本地带盘符路径
        } else {
            // 本地相对路径
            o.path = path.join(__dirname, o.path);
        }
    }
    return o;
}
const _getUrlSource = (url) => {
    // 截取路径源
    const arr = url.split('/');
    const str = arr.slice(0, arr.length - 1).join('/');
    // console.log(url,str)
    return str;
}
const _isHas = (url, arr) => {
    for (let i = 0, len = arr.length; i < len; i++){
        if (arr[i].source === _getUrlSource(url)) {
            return true;
        }
    }
    return false;
}
const download = (url) => { 
    // 下载
    const fileName = getFileName(url);
    let name = fileName.name;
    if (name.indexOf('/') > -1) {
        name = name.split('/');
        name = name[name.length - 1];
    }
    name = [name, fileName.type].join('.');
    const localFinePath = path.join(__dirname, './download_files/' + name);
    console.log('path =>', localFinePath)
    const writeStream = fs.createWriteStream(localFinePath, { autoClose: true });
    const readStream = request(url)
    readStream.pipe(writeStream).on('end', function () {
        console.log('end')
    });
    writeStream.on("finish", function () {
        console.log("finish");
    });
}
const getDownloadFiles = (fileData = '') => {
    const lines = fileData.split('\n');
    let files = [];
    lines.map(line => {
        if (line.indexOf('*') === 0) {
            // 此处为特例
            const links = line.match(/\[(.+?)\]\((.+?)\)/g) || [];
            if (links.length > 0) {
                links.map(link => {
                    const r = link.match(/\]\((.+?)\)/) || [];
                    const href = r[1];
                    // 问题：过滤掉的不会产生替换，此处有漏洞
                    if (href && href.indexOf('http') === 0 && !_isHas(href,files)) {
                        files.push({
                            href,
                            keyword: href,
                            // 判断是否有重
                            source: _getUrlSource(href),
                        });
                    }
                })
            }
        }
    })
    return files;
}
const _newFileName = (filePath = '') => {
    const arr = filePath.split('/');
    let fileName = arr[arr.length - 1];
    const oFileName = getFileName(fileName);
    
    let paths = arr.slice(0, arr.length - 1);
    paths.push([oFileName.name + '_new', oFileName.type].join('.'));
    return paths.join('/');
}
const argv = getArgv();
if (!argv.path) {
    console.error(o.path,'不是有效的路径')
    return;
}

if (argv.type === 'download') {
    download(argv.path) // 下载线上文档 'https://fastly.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js'
} else {
    let mainFile = getFileData(argv.path);
    const files = getDownloadFiles(mainFile);
    files.map(ofile => {
        let newHref = ofile.keyword.match(/\/d3\/d3-(.+?)\//) || [];
        let module_name = newHref[1];
        if (module_name) {
            module_name = 'd3-' + module_name;
            newHref = ['F:/wuwei/js/d3-main/node_modules', module_name, 'README.md'].join('/');
            let mark = ofile.keyword.split('/');
            mark = mark[mark.length - 1] || '';
            mark = mark.split('#');
            if (mark[1]) {
                mark = mark[1];
            } else {
                mark = '';
            }
            if (mark) {
                newHref = [newHref, mark].join('#');
            }
            // console.log(newHref, ofile.keyword)
            mainFile = mainFile.replaceAll(ofile.keyword, newHref);
        } else {
            console.warn('未替换的href', ofile.keyword);
        }
    })
    fileWriteTo(_newFileName(argv.path), mainFile); // 从d3包复制文档到本地目标路径argv.path
}